import { BehaviorSubject } from 'rxjs';
import { Route, Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { ExtendModule } from '../models/module';

@Injectable()
export class RouterService {

    existingRoutes: BehaviorSubject<Route[]>;

    constructor(
        private router: Router
    ) {
        this.existingRoutes = new BehaviorSubject<Route[]>(this.routes);
    }

    private get routes(): Route[] {
        const routes = this.router.config;
        return routes.filter(r => r.path !== '');
    }
    /**
     * 给angular module注册路由
     * @param moduleToRegister 待注册路由的angular module
     * @param exports 加载完成的angular moudle
     * @param prefix 路由的前缀
     */
    createAndRegisterRoute(moduleToRegister: ExtendModule, exports: any, prefix?: string) {
        const path = prefix ? `${prefix}/${moduleToRegister.codeName}` : moduleToRegister.codeName;
        const route: Route = {
            path,
            loadChildren: () => exports[`${moduleToRegister.codeName}`]
        };

        this.registerRoute(route);
    }
    /**
     * 注册路由，放入数组进行管理
     * @param route 注册成功的路由
     */
    registerRoute(route: Route) {
        this.router.config.push(route);
        this.updateRouteConfig(this.router.config);
    }
    /**
     * 更新路由数组
     * @param config 目标路由数组
     */
    private updateRouteConfig(config: Route[]) {
        this.router.resetConfig(config);
        this.existingRoutes.next(this.routes);
    }
}
